package cn.sample.moreitems.particle;

import com.mojang.blaze3d.vertex.VertexConsumer;
import net.minecraft.client.Camera;
import net.minecraft.client.multiplayer.ClientLevel;
import net.minecraft.client.particle.ParticleRenderType;
import net.minecraft.client.particle.SpriteSet;
import net.minecraft.client.particle.TextureSheetParticle;
import net.minecraft.util.Mth;
import net.minecraftforge.api.distmarker.Dist;
import net.minecraftforge.api.distmarker.OnlyIn;
import org.jetbrains.annotations.NotNull;
import org.joml.Vector3f;

@OnlyIn(Dist.CLIENT)
public class CustomExplosionParticle extends TextureSheetParticle {

    private final float shrinkSpeed;
    private static final Vector3f[] BASE = {
            new Vector3f(-1, 0, -1),   // 左下
            new Vector3f(-1, 0,  1),   // 左上
            new Vector3f( 1, 0,  1),   // 右上
            new Vector3f( 1, 0, -1)    // 右下
    };

    public CustomExplosionParticle(ClientLevel level, double x, double y, double z,
                                      double dx, double dy, double dz,
                                      SpriteSet sprites) {
        super(level, x, y, z);
        this.xd = dx;
        this.yd = dy;
        this.zd = dz;
        this.lifetime = 10;
        this.shrinkSpeed = 0.4f;
        this.quadSize = 2.0f;
        this.setSpriteFromAge(sprites);
    }


    @Override
    public void tick() {
        super.tick();
        quadSize -= shrinkSpeed;
        if (quadSize <= 0) remove();
    }

    @Override
    public void render(VertexConsumer buf, Camera camera, float pt) {
        float size = quadSize;
        float u0 = getU0();
        float u1 = getU1();
        float v0 = getV0();
        float v1 = getV1();
        int light = getLightColor(pt);

        // 世界坐标 → 相机相对坐标
        float camX = (float) (Mth.lerp(pt, xo, x) - camera.getPosition().x);
        float camY = (float) (Mth.lerp(pt, yo, y) - camera.getPosition().y);
        float camZ = (float) (Mth.lerp(pt, zo, z) - camera.getPosition().z);

        // 四个顶点：已经平行于地面，无需再 billboard
        for (int i = 0; i < 4; i++) {
            Vector3f p = BASE[i];
            float px = camX + p.x() * size;
            float py = camY + p.y() * size;
            float pz = camZ + p.z() * size;

            buf.vertex(px, py, pz)
                    .uv(i == 0 || i == 3 ? u0 : u1, i < 2 ? v0 : v1)
                    .color(rCol, gCol, bCol, alpha)
                    .uv2(light)
                    .endVertex();
        }
    }


    @Override
    public @NotNull ParticleRenderType getRenderType() {
        return ParticleRenderType.PARTICLE_SHEET_OPAQUE;
    }



}
